package cn.edu.fzu.delivery.handler.impl;

import cn.edu.fzu.delivery.domain.entity.Courier;
import cn.edu.fzu.delivery.domain.entity.SysUser;
import cn.edu.fzu.delivery.domain.enums.NetworkCourierStatusEnum;
import cn.edu.fzu.delivery.handler.DeliveryError;
import cn.edu.fzu.delivery.handler.DeliveryHandler;
import cn.edu.fzu.delivery.handler.DeliverySession;
import cn.edu.fzu.delivery.helper.DingDingRobot;
import cn.edu.fzu.delivery.service.CourierService;
import cn.edu.fzu.delivery.service.LogisticsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * 快递员分配处理器
 *
 * @author fangxin
 * @date 2022/11/7
 */
@Component("courierAllotHandler")
public class CourierAllotHandler implements DeliveryHandler {

    private static final String EMAIL_TITLE   = "派件通知";
    private static final String EMAIL_CONTENT = "亲爱的__NAME__:系统已经给您自动派件，请及时查看";
    private static final String NAME          = "__NAME__";

    @Resource
    private CourierService      courierService;
    @Resource
    private LogisticsService    logisticsService;

    @Override
    public boolean process(DeliverySession session) {
        //可以分配的快递员
        List<SysUser> deliveryMans = session.getDeliveryManPool();
        if (deliveryMans.isEmpty()) {
            session.setError(DeliveryError.NO_DELIVERYMAN);
            return false;
        }
        Random random = new Random();
        //从快递员中随机选一个
        int i = random.nextInt(deliveryMans.size());
        SysUser user = deliveryMans.get(i);
        Courier courier = session.getCourier();
        courierService.allot(courier.getCourierId(), user);
        if(courier.getLogistics() != null) {
            logisticsService.updateStatus(courier.getLogistics().getId(), NetworkCourierStatusEnum.LEAVE);
        }
        //给快递员发钉钉消息
        DingDingRobot.delivery().send(EMAIL_TITLE,
                EMAIL_CONTENT.replace(NAME, user.getName() == null ? "快递员" : user.getName()),
                Collections.singletonList("快递单号：" + courier.getCourierId()), Collections.singletonList(user.getPhone()),
                null);
        return true;
    }

}
